package unitTest.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JSONString;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;


import unitTest.entity.RequestForm;

import com.google.gwt.user.server.rpc.RPCServletUtils;

public class RunTestServlet extends HttpServlet {
	TestRunner testRunner = null;
	JSONSerializer serializer = new JSONSerializer();

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String  payLoad = RPCServletUtils.readContent(req, null,null);
		System.out.println("Received payLoad:" + payLoad);
		Object result = "";

		if (!payLoad.startsWith("getRuntimeResults")) {
			//parse the request JSON string into javabean requestForm
			JSONObject p = (JSONObject) JSONSerializer.toJSON(payLoad);


			RequestForm requestForm = (RequestForm) JSONObject.toBean(p,RequestForm.class);//(RequestForm) JSONSerializer.toJava((JSON)p, jc);

			//start a test runner to simulate the unit test
			testRunner = new TestRunner();
			testRunner.init(requestForm.getCaseNum(), requestForm.getTestSuites());
			testRunner.start();
			System.out.println("firstTime:" + result.toString());
		}

		//get runtime results
		if (testRunner != null) {
			List results = testRunner.getTestResults();
			//transform list of javabeans into JSON string
			result = JSONSerializer.toJSON(results.toArray());
			System.out.println("Return Result:" + result.toString());
		}

		resp.getWriter().write(result.toString());
	}
}
